<?php
/**
 * TAG模块
 */

class Tag_Model extends CI_Model
{
    private $table  = 'tags';
    private $id = 'tag_id';
    
    public function __construct()
    {
        parent::__construct();
    }

    public function doTag($tags=false)
    {
        $tags = $this->formatTag($tags);
        $tags = is_array($tags) && count($tags) > 0 ? implode(',', $tags) : '';
        return $tags;
    }

    public function formatTag($tags=false)
    {
        if(!$tags)
            return '';
        
        //允许中杠和下划线
        $pattern = "/[\~@#\$%\^&\*\.\(\)\[\]\{\}<>\?'\"\\\\\/\s,，\|]+/";
        $tags = trim(preg_replace($pattern, ' ', $tags));
        $tags = explode(' ', $tags);
        if(empty($tags))
            return '';
        return array_unique($tags);
    }

    public function updateNum($num=false, $id=false)
    {
        if(!$num || !count($id))
            return false;

        //set
        $this->db->set('num', $num, false);
        
        //where
        $this->db->where_in($this->id, $id);

        $this->db->update($this->table);
        
        return $this->db->affected_rows();
    }

    public function get($where=false)
    {
        if(!$where)
            return false;
        
        $query = $this->db->get_where($this->table, $where, 1);
        if($query->num_rows() > 0)
        {
            return $query->row();
        }
        else
        {
            return false;
        }
    }

    public function getIdByName($name)
    {
        $tags_id = array();
        
        if(!$name)
            return false;
        if(is_string($name))
            $name = array($name);
        
        foreach($name as $tag_name)
        {
            if(!empty($tag_name))
            {
                $tag = $this->get(array('name' => $tag_name));
                $tags_id[] = $tag->tag_id;
            }
        }
        return $tags_id;
    }

    public function add($name=false)
    {
        if(!$name)
            return false;
        $this->db->insert($this->table, array('name'=>$name));
        if($this->db->affected_rows() > 0)
        {
            return $this->db->insert_id();
        }
        else
        {
            return false;
        }
        
    }

    public function del()
    {
        
    }

    
}